<template>
  <div class="dashboard">
    <div class="dashboard-header">
      <div class="header-content">
        <meter-selector :type="METER_TYPE" class="meter-selector" />
      </div>
    </div>

    <div class="dashboard-content">
      <div class="stats-section">
        <energy-stats-cards :loading="isLoading" />
      </div>

      <div v-if="!isLoading" class="chart-section">
        <energy-chart />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import { storeToRefs } from 'pinia';
import EnergyStatsCards from "./components/EnergyStatsCards.vue";
import EnergyChart from "./components/EnergyChart.vue";
import MeterSelector from "../../../ElectricityData/ElectricityDataCenter/ChartAnalysis/components/MeterSelector.vue";
import { useMeterStore } from "@/stores/meter";
import { useReportStore } from "@/stores/report";
import { useCompanyStore } from "@/stores/company";
import { getMeterDetailApi, getMetersReportApi } from '@/api/meter';
import { getUnknownWaterApi } from "@/api/algorithm";
import { generateTimeConfig } from '@/utils/date';
import dayjs from 'dayjs';
import { handleError } from "@/utils/handleError";
import { getDetailUsageData } from "../../../../../utils/meterUtils";

// 常量
const METER_TYPE = 1;

// Store
const meterStore = useMeterStore();
const reportStore = useReportStore();
const companyStore = useCompanyStore();

// 响应式状态
const { currentMeter, currentSelectedType } = storeToRefs(meterStore);
const { currentCompany } = storeToRefs(companyStore);
const isLoading = ref(false);

// 获取当前配置
const getCurrentConfig = (type = 'day', level = 0) => {
  const config = {
    id: [],
    api: null
  }
  if (type === 'detail') config.api = getMeterDetailApi
  else config.api = getMetersReportApi

  if (currentMeter.value) {
    config.id = [{ id: currentMeter.value.id }];
  } else {
    if (meterStore.meterLevels.length > 0) {
      config.id = [...meterStore.meterLevels[level].map(item => ({ id: item.id }))];
    }
  }
  return config
};

function processedData(data, type = 'day') {
  // 添加空值检查
  if (!data || !data.aggregated_data) {
    console.warn('Invalid data structure received:', data);
    return [];
  }

  return data.aggregated_data.map(item => ({
    time: type === 'half_hour' ? item.end_time : item.start_time,
    value: item.Value
  })) || []
}

// 获取报告数据
const fetchReportData = async (type = 'day') => {
  const config = getCurrentConfig(type);
  if (!config.id) {
    console.warn('No valid ID found for fetching report data');
    return [];
  }
  let offset = 0;
  const timeConfig = generateTimeConfig(type, offset);

  try {
    const res = await config.api({
      meters: config.id,
      ...timeConfig,
      type: currentSelectedType.value
    });

    if (res.code === 200) {
      let data = processedData(res, type);
      const total = data.reduce((acc, cur) => acc + (+cur.value), 0);
      reportStore.updateReportData(type, data, total);
      return data;
    }

    throw new Error(res.message);
  } catch (error) {
    console.error(`Error fetching ${type} report data:`, error);
    throw error;
  }
};

const fetchLastWeekData = async () => {
  const config = getCurrentConfig();
  if (!config.id) return;

  const timeConfigs = [0, 1, 2, 3].map(weekOffset => ({
    start_time: dayjs().subtract(weekOffset, 'week').startOf('week').valueOf(),
    end_time: dayjs().subtract(weekOffset, 'week').endOf('week').add(1, 'day').startOf('day').valueOf(),
    interval: 'day'
  }));

  try {
    const requests = timeConfigs.map(timeConfig => config.api({
      meters: config.id,
      ...timeConfig,
      type: `${currentSelectedType.value}`
    }));
    const results = await Promise.all(requests);

    if (results.every(res => res.code === 200)) {
      for (let i = 0; i <= 3; i++) {
        // 添加数据验证
        const result = results[i];
        if (result && result.aggregated_data) {
          reportStore.updateFourWeekData(i, processedData(results[i]) || []);
        } else {
          console.warn(`Invalid data structure for week ${i}:`, result);
          reportStore.updateFourWeekData(i, []);
        }
      }
      return results;
    }
    throw new Error('Some requests failed');
  } catch (error) {
    handleError(error, '获取上周数据失败');
  }
};

// hour数据
const fetchHourData = async () => {
  if (!currentMeter.value) return;
  const config = getCurrentConfig('detail');
  if (!config.id) return;
  const timeConfig = generateTimeConfig('half_hour', 1);
  try {
    const res = await config.api({
      id: config.id[0].id,
      start_time: timeConfig.start_time,
      end_time: timeConfig.end_time,
      type: 1
    });
    let data = res.meter_readings && res.meter_readings.length > 0 ? res.meter_readings : [];
    data = getDetailUsageData(data);
    const total = data.reduce((acc, cur) => acc + (+cur.value), 0);

    reportStore.updateReportData('half_hour', data, total);
  } catch (error) {
    handleError(error, '获取分时数据失败');
  }
}

// 获取日、月二级表数据
const fetchUnKnownData = async (type) => {
  const timeConfig = generateTimeConfig(type);

  try {
    const res = await getUnknownWaterApi({
      id: companyStore.currentCompany.id,
      ...timeConfig,
    });

    // 添加空值检查
    if (!res || !res.data || !Array.isArray(res.data)) {
      console.warn(`获取${type}未知数据失败: 返回数据格式不正确`, res);
      reportStore.updateUnKownWaterReportData(type, []);
      return;
    }

    const data = res.data.map(item => {
      // 添加项目级别的空值检查
      if (!item || !item.data || typeof item.data.unknown_water === 'undefined' || typeof item.data.top_usage === 'undefined') {
        console.warn(`${type}数据中存在无效项`, item);
        return {
          time: item?.start_time || 0,
          value: "0.00"
        };
      }

      // 避免除以零的情况
      const topUsage = parseFloat(item.data.top_usage);
      if (topUsage === 0) {
        return {
          time: item.start_time,
          value: "0.00"
        };
      }

      return {
        time: item.start_time,
        value: ((+item.data.unknown_water / topUsage) * 100).toFixed(2)
      };
    });

    reportStore.updateUnKownWaterReportData(type, data);
  } catch (error) {
    console.error(`获取${type}未知数据出错:`, error);
    handleError(error, `获取${type}数据失败`);
    reportStore.updateUnKownWaterReportData(type, []);
  }
}

// 数据加载
const loadData = async () => {
  reportStore.resetReportData()
  try {
    await fetchHourData();
    const reportTypes = ['day', 'month', 'quarter', 'year'];
    for (let i = 0; i < reportTypes.length; i++) {
      const type = reportTypes[i];
      await fetchReportData(type)
    }
    await fetchLastWeekData();
    reportTypes.slice(0, 2).forEach(type => fetchUnKnownData(type));
  } catch (error) {
    handleError(error, '数据加载错误');
  }
};

let getComparisonTimeConfig = (type, comparisonType) => {
  let map = {
    'half_hour': 'day',
    'day': 'month',
    'month': 'year'
  }
  switch (comparisonType) {
    case 'last_period':
      return type === 'half_hour' ? generateTimeConfig(type, 2) : generateTimeConfig(type, 1); // 获取上一个周期
    case 'last_year':
      let end_time = type === 'half_hour' ? generateTimeConfig(type, 1).end_time : generateTimeConfig(type).end_time;
      let start_time = 'half_hour' ? generateTimeConfig(type, 1).start_time : generateTimeConfig(type).start_time;
      return {
        start_time: dayjs(start_time).subtract(1, 'year').valueOf(),
        end_time: dayjs(end_time).subtract(1, 'year').valueOf(),
        interval: type
      };
    case 'custom':
      const date = reportStore.chartState.comparisonDate;
      if (!date) return null;
      let range = map[type];
      return {
        start_time: dayjs(date).startOf(range).valueOf(),
        end_time: dayjs(date).endOf(range).add(1, 'day').startOf('day').valueOf(),
        interval: type
      };
    default:
      return null;
  }
}

// 获取对比数据
const fetchComparisonData = async (type, comparisonType) => {
  const config = getCurrentConfig(type);
  if (!config.id) return;
  let timeConfig = getComparisonTimeConfig(type, comparisonType);
  if (!timeConfig) return;
  try {
    const res = await config.api({
      meters: config.id,
      ...timeConfig,
      type: currentSelectedType.value
    });

    if (res.code === 200) {
      const data = processedData(res, type);
      reportStore.updateComparisonData(type, data);
    }
  } catch (error) {
    handleError(error, '获取对比数据失败');
  }
};

watch(() => reportStore.chartState, async (newState) => {
  const { period, comparison } = newState;
  if (['half_hour', 'day', 'month'].includes(period) && comparison !== 'none') {
    await fetchComparisonData(period, comparison);
  }
}, { deep: true });

// 重置仪表数据
const resetMeterData = () => {
  reportStore.resetReportData()
  meterStore.setCurrentMeter(null);
  meterStore.setCurrentSelectedType(METER_TYPE);
};

async function getMeterList() {
  try {
    await meterStore.fetchMeterList({
      company_id: currentCompany.value.id,
      type: currentSelectedType.value
    })
  } catch (error) {
    handleError(error, '获取表计列表失败');
  }
}

watch(currentMeter, async () => {
  try {
    isLoading.value = true;
    await loadData()
  } catch (error) {
    handleError(error, '数据加载失败');
  } finally {
    isLoading.value = false;
  }
})

watch(
  currentCompany,
  async () => {
    isLoading.value = true;
    resetMeterData();
    await getMeterList();
    await loadData();
    isLoading.value = false;
  }, {
  immediate: true,
  deep: true
});
</script>

<style scoped>
.dashboard {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  box-sizing: border-box;
}


.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 100%;
}

.meter-selector {
  flex: 1;
  max-width: 100%;
}

.dashboard-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.stats-section {
  flex-shrink: 0;
}

.chart-section {
  flex: 1;
  min-height: 400px;
  display: flex;
  flex-direction: column;
}

.loading-section {
  flex: 1;
  min-height: 300px;
  padding: 1rem 0;
}

/* 平板端适配 */
@media screen and (max-width: 1400px) and (min-width: 769px) {
  .header-content {
    padding: 0 0.8rem;
  }

  .dashboard-content {
    padding: 0.8rem;
    gap: 0.8rem;
  }

  .chart-section {
    min-height: 350px;
  }
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .dashboard-header {
    position: sticky;
    top: 0;
  }

  .header-content {
    padding: 0 1rem;
    flex-direction: column;
    justify-content: center;
  }

  .meter-selector {
    width: 100%;
  }

  .dashboard-content {
    padding: 0.75rem;
    gap: 1rem;
    padding-bottom: 2rem;
    /* 底部额外间距 */
  }

  .chart-section {
    min-height: 300px;
  }

  .loading-section {
    min-height: 250px;
  }

  /* 优化移动端滚动 */
  .dashboard-content {
    -webkit-overflow-scrolling: touch;
    scroll-behavior: smooth;
  }
}
</style>